package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UserIntercept implements HandlerInterceptor {
    @Autowired
     private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头中的令牌
        String token = request.getHeader("authorization");
        //令牌为空就抛异常返回
        //不为空就解析
        if (ObjectUtil.isNull(token)) {
            response.setStatus(401);
            return false;
        }
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if (ObjectUtil.isNull(claims)) {
            response.setStatus(401);
            return false;
        }
        //TODO
        Long id = Long.valueOf((Integer) claims.get(Constants.JWT_USERID));
        UserThreadLocal.set(id);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
